<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#myCanvas{
	background-color:#CCC;
	border:solid thin  #666;
}
</style>
</head>

<body>
<canvas id="myCanvas" width="640" height="480"></canvas>
</body>
</html>

<script language="javascript">
	window.onload = function()
	{	
		var screenWidth = 640;
		var screenHeight = 480;		
		var canvas = document.getElementById("myCanvas");
		var context = canvas.getContext("2d");	
		var m = new Array();
		
		var mousestate = "mouseup";
		var mousex = null;
		var mousey = null;

		
		function tbox(){
			this.x = null;
			this.y = null;
			this.width = null;
			this.height = null;
			this.name = null;
			
			this.clickme = function(context){				
				if ( mousestate == "mousedown" ){
					if ( this.x < mousex && mousex < (this.x + this.width) && this.y < mousey && mousey < (this.y + this.height) ){
						alert( this.name );
						mousestate = "mouseup";
					}
				}		

			}
		}
		
		for ( var i = 0; i < 10; i++)
		{
			m[i] = new tbox();
			m[i].name = "I am mr.number" + i;
			m[i].x = Math.random() * screenWidth;
			m[i].y = Math.random() * screenHeight;
			m[i].width = Math.random() * 100;
			m[i].height = Math.random() * 100;
			

		}
		
		

		setInterval(mainLoop, 10);
		
		
		function mainLoop()
		{	
			// Clear Screen			
			context.clearRect(0, 0, screenWidth, screenHeight);									

			context.fillText( "Example: HTML5 Test Boxes", 20 , 20 );						
			context.fillText( "Mouse X: " + mousex, 20, 40 );
			context.fillText( "Mouse Y: " + mousey, 20, 60 );
			context.fillText( "Mouse State: " + mousestate, 20, 80 );					
			
			for ( var i = 0; i < m.length; i++)
			{
				context.beginPath();				
				draw(m[i]);				
				context.closePath();
				context.stroke();				
			}		
			
			for ( var i = 0; i < m.length; i++ )
			{
				m[i].clickme();
			}
			
		}
		
		function draw(obj)
		{

			context.rect( obj.x, obj.y, obj.width, obj.height );

		}
		
		canvas.onmousemove = function(e)
		{
			mousex = e.layerX - canvas.offsetLeft;
			mousey = e.layerY - canvas.offsetTop;
		}
		
		canvas.onmousedown = function(e)
		{
			mousestate = "mousedown";
		}
		
		canvas.onmouseup = function(e)
		{
			mousestate = "mouseup";
		}
		
		
		
		
	}
	
	
</script>
